#include "OutPlayOpponentBehaviour.h"

/*
 *	Hrac si predkopne loptu popri superovi, bod na ktory sa predkopne lopta si spravanie samo 
 *  vypocita na zaklade svojej pozicie a pozicie najblizsieho supera
 *
 */
void OutPlayOpponentBehaviour::Behave()
{
	Point myPosition = world->me->pos;

	Player nearestEnemy = GetNearestEnemy(myPosition);
	Vector vectFromMeToEnemy = (nearestEnemy.pos - myPosition);

	float lfDistance = vectFromMeToEnemy.GetLength();

	if(lfDistance >= 0)
	{
		if(vectFromMeToEnemy.GetAngle().GetDeg() > 0)
			vectFromMeToEnemy.SetAngle(vectFromMeToEnemy.GetAngle() - DegAngle(42));
		else
			vectFromMeToEnemy.SetAngle(vectFromMeToEnemy.GetAngle() + DegAngle(42));
	}
	else
	{
		Point tmpTargetPoint(myPosition.GetX() + 3, myPosition.GetY());
		vectFromMeToEnemy = tmpTargetPoint - myPosition;
	}

	double lfPassSpeed = (fabs(lfDistance) - lfMinPassDistance) / (lfMaxPassDistance - lfMinPassDistance) * (world->params->server->ball_speed_max - 1.3) +  1.3;
	
	GetPassBallToBehaviour()->Behave(myPosition + vectFromMeToEnemy, GetPassBallToBehaviour()->CorrectPassSpeed((float)lfPassSpeed));
 	GetTurnNeckToBehaviour()->Behave(myPosition + vectFromMeToEnemy, world->ball->pos, 0);
}


/*
* Vrati najblizsi index supera od zadaneho bodu
*
* @param target
*/
Player OutPlayOpponentBehaviour::GetNearestEnemy(const Point& target)
{
	float min = 1000.0;
	int player = -1;

	for(int i = 0; i < world->enemies.GetSize(); i++)
	{
		float diff = (world->enemies[i].pos - target).GetLength();
		if(diff < min)
		{
			min = diff;
			player = i;
		}
	}

	return world->enemies[player];
}
